var api = require("./api_v1")
var jwt = require('../lib/jsonwebtoken')

/* GET home page. */

signIn = {
  path: "/signin",
  method: "post",
  executor: function(req, res, next) {
    model.User.findOne({where: req.body}).then(user => {
      if(null == user) {
        res.send(util.signinError("用户名或密码错误"))
      } else if(1 == user.status) {
        res.send(util.signinError("用户被限制登录"))
      } else {
        var expire = new Date(Date.now()+3*24*3600*1000);
        jwt.sign({account: user.get("account")}, (err, token) => {
          res.cookie('Authorization', token, { expires: expire, httpOnly: true , signed: true});
          res.send(util.responseOk())
        })
      }
    })
  },
}

signUp = {
  path: "/signup",
  method: "post",
  executor: function(req, res, next) {
    model.sequelize.transaction(t => {
      return model.User.findOne({where: {code: req.body.code}}, {transaction: t})
    }).then(introducer => {
      if( null == introducer) {
        throw new Error("邀请码不存在")
      } else {
        // 使用邀请码
        return introducer.update({code_use: introducer.code_use-1})
      }
    }).then(introducer => {
      if(introducer.code_use < 0) {
        throw new Error("邀请人的邀请次数已用完")
      } else {
        return model.User.create({
          account: req.body.account,
          password: req.body.password,
          introducer: introducer.id,
          code: util.codeGenerate(),
          code_use: 3,
          status: 0
        })
      }
    }).then(user => {
      res.send(util.responseOk(user.dataValues));
    }).catch(err => {
      res.send(util.supportError(err.message))
    });
  },
}

signOut = {
  path: "/signout",
  method: "delete",
  executor: function(req, res, next) {
      res.clearCookie('Authorization')
      res.send(util.responseOk())
  },
}

whoAmI = {
  path: "/whoami",
  method: "get",
  executor: function(req, res, next) {
    var token = req.signedCookies.Authorization
    jwt.verify(token, (err, decode) => {
      if(err) {
        res.send(util.responseOk({
          id: 0,
          account: "anonymous"
        }))
      } else {
        model.User.findOne({where: {account: decode.account}}).then(user => {
          res.send(util.responseOk(user.dataValues))
        })
      }
    })
  },
}

router = {
  type: "router",
  prefix: false,
  locations: [
      signIn,
      signUp,
      signOut,
      whoAmI
  ]
}

module.exports = api.register(router)
